from sanic import Blueprint, Sanic, json

from app.core.entity import ApiResult
from app.core.exception import ApiException
from app.utils.Aliyun.AliyunSmsUtils import AliyunSmsUtils
from app.utils.CaptchaUtils import CaptchaUtils
from app import myApp

bp=Blueprint("common",url_prefix="/common")

@bp.route('/captcha',methods=['GET'])
async def captcha(request):
    captcha=CaptchaUtils()
    captcha.generate()
    b64=captcha.toBase64Browser()
    captcha.cache()
    return json(vars(ApiResult.success(data={"base64":b64,"key":captcha.key})))

@bp.route("/captcha/phone",methods=['POST'])
async def captchaPhone(request):
    data=request.load_json()
    if(len(data['phone'])==0):
        raise ApiException("没有填写手机号")
    captcha=CaptchaUtils().setLength(6).setCaptchaType(3).generate().cache()
    respData={"key":captcha.key,"value":captcha.result}
    print(myApp.config['app']['debug'])
    if myApp.config['app']['debug']!="Y":
        respData['value']=""
        sms=AliyunSmsUtils()
        sms.smsSignName="小程序AA小助手"
        sms.sendMessage(data['phone'],"SMS_279295761",{"code":captcha.result})
    return json(vars(ApiResult.success(data=respData)))
